package com.situ.company.service.impl;

import java.util.List;

import com.situ.company.dao.IUserDao;
import com.situ.company.dao.IUserRoleDao;
import com.situ.company.dao.impl.UserDaoImpl;
import com.situ.company.dao.impl.UserRoleDaoImpl;
import com.situ.company.entity.User;
import com.situ.company.service.IUserService;
import com.situ.company.util.JSONResult;
import com.situ.company.vo.PageInfo;
import com.situ.company.vo.UserInfoVO;
import com.sun.jndi.toolkit.url.Uri;

public class UserServiceImpl implements IUserService{
	private IUserDao userDao = new UserDaoImpl();
	private IUserRoleDao userRoleDao = new UserRoleDaoImpl();

	@Override
	public List<User> selectAll() {
		return userDao.selectAll();
	}

	@Override
	public PageInfo selectByPage(int pageNo, int pageSize) {
		int offset = (pageNo - 1) * pageSize;
		List<User> list = userDao.selectByPage1(offset, pageSize);
		
		int totalCount = userDao.selectTotalCount("");
		int totalPage = (int)Math.ceil((double)totalCount / pageSize);
		
		PageInfo pageInfo = new PageInfo(pageNo, pageSize, list, totalPage);
		
		return pageInfo;
	}

	@Override
	public boolean deleteById(int id) {
		int count = userDao.deleteById(id);
		return count == 1;
	}

	@Override
	public JSONResult selectLayuiByPage(String name, Integer page, Integer limit) {
		int offset = (page - 1) * limit;
		List<UserInfoVO> list = userDao.selectByPage(name, offset, limit);
		
		int totalCount = userDao.selectTotalCount(name);
		
		JSONResult jsonResult = new JSONResult(JSONResult.OK, "", list, totalCount);
		return jsonResult;
	}

	@Override
	public boolean deleteAll(String[] ids) {
		int count = 0;
		for (String id : ids) {
			count += userDao.deleteById(Integer.parseInt(id));
		}
		return count == ids.length;
	}

	@Override
	public boolean insert(User user, String[] roleIds) {
		// 将User对象插入到user表，并返回自增的id
		int id = userDao.insert(user);
		// 用户选择的角色插入到user_role表
		for (String roleId : roleIds) {
			userRoleDao.insert(id, Integer.parseInt(roleId));
		}
		
		return true;
	}

	@Override
	public User selectById(int id) {
		return userDao.selectById(id);
	}

	@Override
	public boolean update(User user, String[] roleIds) {
		userDao.update(user);
		// 1,1			1,2
		// 1,2			1,3
		// 1,3
		userRoleDao.deleteByUserId(user.getId());
		for (String id : roleIds) {
			userRoleDao.insert(user.getId(), Integer.parseInt(id));
		}
		return true;
	}

}
